<?php

namespace App\Admin\Controllers\Kly;

use App\Models\kly\Kly_camp;
use App\Models\kly\Kly_notice;
use App\Models\kly\Kly_record;
use App\Models\kly\Kly_report;
use App\Models\kly\kly_setting;
use App\Models\Kly\kly_student;
use App\Models\Student;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Form;
use Encore\Admin\Facades\Admin;
use App\Models\Squad;
use http\Env\Response;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;


use App\Models\Class_section_group;


class Kly_reportController extends Controller
{
    use ModelForm;
    private $class;


    public function __construct()
    {
		// $arr = DB::table("kly_notice")->getArr(['id','starttime']);
		// foreach($arr as $v){
		// 	DB::table("kly_notice")->where('id',$v['id'])->update([
		// 		'starttime' => date("Y-m-d H:i:s",strtotime($v['starttime']) - 2592000)
		// 	]);
		// }
		// exit("done");
    }

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Content $content)
    {
        $content->header('报表详情');
        $content->description('详情');
        $content->row($this->grid());
        return $content;
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {

    }


    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {

    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $type = request('type');
        return Admin::grid(kly_report::class,function(Grid $grid) use ($type) {
            if($type == 'day'){
                $type = '1';
            }elseif($type == 'week'){
                $type = '2';
            }elseif($type == 'full'){
                $type = '3';
            }

            $id = Admin::user()->id;
            $camps = DB::table('kly_camps')->where('tutors',$id)->orWhereRaw('find_in_set('.$id.',`aids`)')->get();
            $small_camps = array(0);
            foreach($camps as $v){
                $small_camps[] = $v->id;
            }
            $grid->model()->where('pid',0)->where('type',$type)->whereIn('small_camp',$small_camps);
            $grid->orderBy('id','desc');

            $grid->name('名称');
            $grid->column('大营')->display(function(){
               $pid = Kly_camp::find($this->small_camp)->pid;
               return Kly_camp::find($pid)->name;
            });
            $grid->column('小营')->display(function(){
                return Kly_camp::find($this->small_camp)->name;
            });
            $grid->type('类型')->display(function(){
                if($this->type == '1'){
                    return '日报';
                }elseif($this->type == '2'){
                    return '周报';
                }elseif($this->type == '3'){
                    return '整报';
                }else{
                    return '';
                }
            });
            $grid->start_time('开始时间');
            $grid->end_time('结束时间');

            $grid->column('操作')->display(function(){
                $html = '<a class="btn btn-success" href="/admin/kly_report_list?pid='.$this->id.'">个人报表</a>';
                return $html;
            });

            $grid->disableActions();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Squad::class,function (Form $form) {
            $form->setTitle('查看');
            $form->row(function ($row) use ($form)
            {
                $id = Admin::user()->id;
                $row->width(4)->select('section', trans('admin.section'))->options(function(){
                    return Class_section_group::regulate_options(2);
                })->attribute(['id'=>'section'])->Myload('group', '/api/get_group_user',$id)->rules('required');
                $row->width(4)->select('group',trans('admin.group'))->options(function ($id){
                    return Class_section_group::options($id);
                })->attribute(['id'=>'group'])->Myload('squad','/api/get_squads_user',$id)->rules('required');
                $row->width(4)->select('squad',trans('admin.squad'))->attribute(['id'=>'squad'])->load('student','/api/get_students')->rules('required');
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $row->width(4)->select('student','学生id-姓名')->attribute(['id'=>'student'])->rules('required');
                //$row->width(4)->text('start_time','开始时间(包含)')->attribute(['id'=>'startTime']);
                //$row->width(4)->text('end_time','结束时间(包含)')->attribute(['id'=>'endTime']);
                $row->width(4)->date('start_time','开始时间(包含)')->attribute(['id'=>'startTime','style'=>'width:350px;']);
                $row->width(4)->date('end_time','结束时间(包含)')->attribute(['id'=>'endTime','style'=>'width:350px;']);
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $status = array();
                $status = array('1'=>'听写','2'=>'测验','3'=>'考勤','4'=>'家校','5'=>'作业');
                $row->width(4)->multipleSelect('type','类型')->options($status)
                    ->attribute(['id'=>'type']);
                $row->width(4)->html('<textarea placeholder="请填写评语,填写时使用回车换行，方便排版。" id="memo" style="height:150px;resize:none;width:396px;margin-left:12px;"></textarea>
<span class="nl_zsjc"><i class="nlysrzs">0</i>/<em class="nlzzts">160</em> 个字</span>');
                $row->width(4)->html('<button style="margin-left:170px;" type="button" id="btn_submit" class="btn btn-primary">查询</button><button style="" type="button" id="btn_pdf" class="btn btn-danger" onclick="o_window()">导出PDF</button>');
            },  $form);

            $form->disableSubmit();
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    public function report_list(Content $content)
    {
        $content->header('报表详情');
        $content->description('详情');
        $content->row($this->list_grid());
        return $content;
    }

    protected function list_grid()
    {
        $id = request('pid');
        return Admin::grid(kly_report::class,function(Grid $grid) use ($id) {
            $grid->model()->where('pid','=',intval($id));
            $grid->id(trans('admin.ID'))->sortable();

            $grid->student('学生')->display(function(){
               $stu = Student::find($this->student);
               return $stu->en_name.'-'.$stu->ch_name;
            });
            $grid->column('名称')->display(function() use ($id){
                return Kly_report::find($id)->name;
            });
            $grid->column('大营')->display(function() use ($id){
                $pid = Kly_camp::find(Kly_report::find($id)->small_camp)->pid;
                return Kly_camp::find($pid)->name;
            });
            $grid->column('小营')->display(function() use ($id){
                return Kly_camp::find(Kly_report::find($id)->small_camp)->name;
            });
            $grid->column('开始时间')->display(function() use ($id){
                return Kly_report::find($id)->start_time;
            });
            $grid->column('结束时间')->display(function() use ($id){
                return Kly_report::find($id)->end_time;
            });

            $grid->column('操作')->display(function() use ($id){
                $html = '<a class="btn btn-success" href="/admin/kly_report_detail?id='.$this->student.'&pid='.$id.'">查看</a>';
                return $html;
            });

            $grid->disableActions();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();
        });
    }

    public function report_print(Content $content)
    {
/*        $content->header(' ');
        $content->description(' ');
        $content->row(view('admin.kly.report_view'));
        return $content;*/
return view('admin.kly.report_view');
    }


    public function report_get(Request $request)
    {
        $report = Kly_report::find($request['id']);
        if(isset($report->memo) && !is_null($report->memo)){
            $memo = json_decode($report->memo,true);
        }else{
            $memo = array();
        }

        $camp_id = $report->small_camp;
        $camp_temp = Kly_camp::find($camp_id);

        $tutor = Administrator::where('id',$camp_temp->tutors)->pluck('username');
        $camp_name = $camp_temp->name;
        $start_time = $report->start_time;
        $end_time = $report->end_time;

        $time_begin = '2019-07-28 00:00:00';
        $begin = (strtotime($start_time) - strtotime($time_begin))/3600/24;
        $end = (strtotime($end_time) - strtotime($time_begin))/3600/24;
        $time_arr = $times_arr = array();
        for($t=$begin;$t<=$end;$t++){
            $time_arr[] = date('m-d',strtotime($time_begin.'+'.$t.' days'));
            $times_arr[] = $t;
        }

        $students = DB::table('students as s')->join('kly_students as ks','ks.student_id','=','s.id')
            ->where('ks.small_camp_id','=',$camp_id)
            ->get(['s.id','s.en_name','s.ch_name']);
        $stuArr = array();
        foreach($students as $v){
            $stuArr[$v->id]['en_name'] = $v->en_name;
            $stuArr[$v->id]['ch_name'] = $v->ch_name;
        }

        //大营id
        $camp_pid = Kly_camp::find($camp_id)->pid;
        $big_camp = Kly_camp::find($camp_pid)->name;
        $settingP = kly_setting::where('camp_id',$camp_pid)->pluck('id');
        $bigcamp_setting = kly_setting::where('camp_id',$camp_pid)->get(['cover','background','color'])->toArray();
        $color = array();

        foreach($bigcamp_setting as $k => $v){
            $bigcamp_setting[$k]['cover'] = URL::asset($v['cover']);
            $bigcamp_setting[$k]['background'] = URL::asset($v['background']);
            if($v['color'] == 1){
                //museum 灰色
                $color = array('image'=>array('#FFF','#fdd42a','#b4b4b5'),'axis'=>'white','text'=>'white','split'=>'rgba(255,255,255,0.8)','image_display'=>'white');
            }elseif($v['color'] == 2){
                //writing 橙色
                $color = array('image'=>array('#FFF','#EB6363','#FDD23E'),'axis'=>'white','text'=>'white','split'=>'rgba(255,255,255,0.8)','image_display'=>'white');
            }elseif($v['color'] == 3){
                //speak 黑色
                $color = array('image'=>array('#EA5A5A','#DFCD5D','#71C3AA'),'axis'=>'white','text'=>'white','split'=>'rgba(255,255,255,0.8)','image_display'=>'white');
            }elseif($v['color'] == 4){
                //broadway 白色
                $color = array('image'=>array('#e73926','#fdd42a','#fbf1d1'),'axis'=>'#000','text'=>'#000','split'=>'rgba(100,100,100,0.5)','image_display'=>'#000');
            }elseif($v['color'] == 5){
                //science 蓝色
                $color = array('image'=>['#99CCFF','#CCFFFF','#6699CC'],'axis'=>'#000','text'=>'#000','split'=>'#F0F0F1','image_display'=>'#000');
            }
            unset($bigcamp_setting[$k]['color']);
        }

        $setting = kly_setting::where('pid',$settingP)->get()->toArray();

        $is_radar = 0;
        $settingArr = array();
        foreach($setting as $v){
            if($v['tag'] == 'radar'){
                $is_radar = 1;
            }
            $settingArr[$v['tag']] = $v;
        }

        //大营下所有小营
        $camps = Kly_camp::where('pid',$camp_pid)->pluck('id')->toArray();

        //计算大营平均分和状态情况
        // if($big_camp == "Wonder Museum"){
        //     if($camp_id >= 41 && $camp_id <= 49){
        //         $bigCamp_statusData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
        //             ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
        //             ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
        //             ->whereIn('n.status',['2','4'])->whereIn('n.camp_id',$camps)
        //             ->groupBy(['n.tag','kr.status'])->orderBy('n.id','asc')
        //             ->whereBetween("n.camp_id",[41,49])
        //             ->select(DB::raw('count(1) as num'),'n.tag','kr.status')->get();
        //     }else{
        //         $bigCamp_statusData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
        //             ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
        //             ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
        //             ->whereIn('n.status',['2','4'])->whereIn('n.camp_id',$camps)
        //             ->groupBy(['n.tag','kr.status'])->orderBy('n.id','asc')
        //             ->whereBetween("n.camp_id",[50,57])
        //             ->select(DB::raw('count(1) as num'),'n.tag','kr.status')->get();
        //     }
        // }else{
             $bigCamp_statusData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
            ->whereIn('n.status',['2','4'])->whereIn('n.camp_id',$camps)
            ->groupBy(['n.tag','kr.status'])->orderBy('n.id','asc')
            ->select(DB::raw('count(1) as num'),'n.tag','kr.status')->get();
        // }
        $bigCamp_statusData = json_decode(json_encode($bigCamp_statusData),true);
        $bigCamp_statusArr = array();
        $tagArr = array();

        foreach($bigCamp_statusData as $v){
            if(!isset($bigCamp_statusArr[$v['tag']])){
                $bigCamp_statusArr[$v['tag']] = array();
            }
            if(!in_array($v['tag'],$tagArr)){
                $tagArr[] = $v['tag'];
            }
            $bigCamp_statusArr[$v['tag']][$v['status']] = $v['num'];
        }

        if($big_camp == "Science Festiva"){
           $bigCamp_scoreData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereIn('n.status',['2','4'])->whereIn('n.camp_id',$camps)
            ->where('kr.score','>',0)
            ->groupBy(['n.tag','n.times'])->orderBy('n.id','asc')
            ->select(DB::raw('ROUND(avg(kr.score),2) as avg'),'n.tag','n.times')->get();
        }else{
            $bigCamp_scoreData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
            ->whereIn('n.status',['2','4'])->whereIn('n.camp_id',$camps)
            ->where('kr.score','>',0)
            ->groupBy(['n.tag','n.times'])->orderBy('n.id','asc')
            ->select(DB::raw('ROUND(avg(kr.score),2) as avg'),'n.tag','n.times')->get();
        }
        $bigCamp_scoreData = json_decode(json_encode($bigCamp_scoreData),true);

        $newArr = array();
        $timesArr = array();

        if($big_camp == 'Speak Great'){
            foreach($bigCamp_scoreData as $v){
                if(!isset($timesArr[$v['tag']])){
                    $timesArr[$v['tag']] = array();
                }
                $timesArr[$v['tag']][] = $v['times'];
            }

            foreach($timesArr as $k=>$v){
                $times_diff = array_diff($times_arr,$v);
                if(count($times_diff) > 0){
                    foreach($times_diff as $_v){
                        $bigCamp_scoreData[] = array('times'=>$_v,'tag'=>$k,'avg'=>'');
                    }
                }
            }


            $sort1 = $sort2 = array();
            foreach($bigCamp_scoreData as $k=>$v){
                $sort1[$k] = $v['times'];
                $sort2[$k] = $v['tag'];
            }
            array_multisort($sort2,SORT_ASC,$sort1,SORT_ASC,$bigCamp_scoreData);
        }
        foreach($bigCamp_scoreData as $v){
            if(!isset($newArr[$v['tag']])){
                $newArr[$v['tag']] = array();
            }
            $newArr[$v['tag']][] = $v['avg'];
        }

        foreach($timesArr as $k => $v){

        }

        $bigCamp_scoreArr = array();
        foreach($bigCamp_scoreData as $v){
            if(!isset($bigCamp_scoreArr[$v['tag']])){
                $bigCamp_scoreArr[$v['tag']] = array();
            }
            if(!in_array($v['tag'],$tagArr)){
                $tagArr[] = $v['tag'];
            }
            $bigCamp_scoreArr[$v['tag']] = $newArr[$v['tag']];
        }

        if($big_camp == 'Speak Great'){
            $tagArr = array('kaoqin','zuoye','words_exam','toef');
        }

        //计算小营平均分和状态情况
        $smallCamp_statusData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
            ->whereIn('n.status',['2','4'])->where('n.camp_id',$camp_id)
            ->groupBy(['n.tag','kr.status'])
            ->select(DB::raw('count(1) as num'),'n.tag','kr.status')->get();
        $smallCamp_statusData = json_decode(json_encode($smallCamp_statusData),true);
        $smallCamp_statusArr = array();

        foreach($smallCamp_statusData as $v){
            if(!isset($smallCamp_statusArr[$v['tag']])){
                $smallCamp_statusArr[$v['tag']] = array();
            }
            $smallCamp_statusArr[$v['tag']][$v['status']] = $v['num'];
        }

        if($big_camp == "Science Festiva"){
            $smallCamp_scoreData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereIn('n.status',['2','4'])->where('n.camp_id',$camp_id)
            ->where('kr.score','>',0)
            ->groupBy(['n.tag','n.id','n.times'])
            ->select(DB::raw('ROUND(avg(kr.score),2) as avg'),'n.tag','n.id','n.times')->get();
        }else{
            $smallCamp_scoreData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
            ->whereIn('n.status',['2','4'])->where('n.camp_id',$camp_id)
            ->where('kr.score','>',0)
            ->groupBy(['n.tag','n.id','n.times'])
            ->select(DB::raw('ROUND(avg(kr.score),2) as avg'),'n.tag','n.id','n.times')->get();
        }
        $smallCamp_scoreData = json_decode(json_encode($smallCamp_scoreData),true);

        $timesArr = array();
        if($big_camp == 'Speak Great'){
            foreach($smallCamp_scoreData as $v){
                if(!isset($timesArr[$v['tag']])){
                    $timesArr[$v['tag']] = array();
                }
                $timesArr[$v['tag']][] = $v['times'];
            }

            foreach($timesArr as $k=>$v){
                $times_diff = array_diff($times_arr,$v);
                if(count($times_diff) > 0){
                    foreach($times_diff as $_v){
                        $smallCamp_scoreData[] = array('times'=>$_v,'tag'=>$k,'avg'=>'');
                    }
                }
            }


            $sort1 = $sort2 = array();
            foreach($smallCamp_scoreData as $k=>$v){
                $sort1[$k] = $v['times'];
                $sort2[$k] = $v['tag'];
            }
            array_multisort($sort2,SORT_ASC,$sort1,SORT_ASC,$smallCamp_scoreData);
        }

        $smallCamp_scoreArr = array();
        foreach($smallCamp_scoreData as $v){
            if(!isset($smallCamp_scoreArr[$v['tag']])){
                $smallCamp_scoreArr[$v['tag']] = array();
            }
            $smallCamp_scoreArr[$v['tag']][$v['times']] = $v['avg'];
        }

        //计算个人平均分和状态情况
        $person_statusData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
            ->whereIn('n.status',['2','4'])->where('n.camp_id',$camp_id)
            ->groupBy(['n.tag','kr.status','kr.student_id'])
            ->select(DB::raw('count(1) as num'),'n.tag','kr.status','kr.student_id')->get();
        $person_statusData = json_decode(json_encode($person_statusData),true);

        $person_statusArr = array();

        foreach($person_statusData as $v){
            if(!isset($person_statusArr[$v['student_id']][$v['tag']])){
                $person_statusArr[$v['student_id']][$v['tag']] = array();
            }
            $person_statusArr[$v['student_id']][$v['tag']][$v['status']] = $v['num'];
        }
        if($big_camp == "Science Festiva"){
            $person_scoreData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereIn('n.status',['2','4'])->where('n.camp_id',$camp_id)
            ->where('kr.score','>=',0)
            ->groupBy(['n.tag','n.id','kr.student_id','n.times'])
            ->select(DB::raw('ROUND(avg(kr.score),2) as avg'),'n.tag','n.id','kr.student_id','n.times')->get();
        }else{
            $person_scoreData = DB::table('kly_notice as n')->join('kly_records as kr','kr.notice_id','=','n.id')
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) <='.strtotime($end_time))
            ->whereRaw('UNIX_TIMESTAMP(n.starttime) >='.strtotime($start_time))
            ->whereIn('n.status',['2','4'])->where('n.camp_id',$camp_id)
            ->where('kr.score','>=',0)
            ->groupBy(['n.tag','n.id','kr.student_id','n.times'])
            ->select(DB::raw('ROUND(avg(kr.score),2) as avg'),'n.tag','n.id','kr.student_id','n.times')->get();
        }
        $person_scoreData = json_decode(json_encode($person_scoreData),true);

        $timesArr = array();
        if($big_camp == 'Speak Great'){
            foreach($person_scoreData as $v){
                if(!isset($timesArr[$v['student_id']][$v['tag']])){
                    $timesArr[$v['student_id']][$v['tag']] = array();
                }
                $timesArr[$v['student_id']][$v['tag']][] = $v['times'];
            }

            foreach($timesArr as $k=>$v){
                foreach($v as $key => $value){
                    $times_diff = array_diff($times_arr,$value);
                    if(count($times_diff) > 0){
                        foreach($times_diff as $_v){
                            $person_scoreData[] = array('times'=>$_v,'tag'=>$key,'avg'=>'','student_id'=>$k);
                        }
                    }
                }
            }


            $sort1 = $sort2 = array();
            foreach($person_scoreData as $k=>$v){
                $sort1[$k] = $v['times'];
                $sort2[$k] = $v['tag'];
            }
            array_multisort($sort2,SORT_ASC,$sort1,SORT_ASC,$person_scoreData);
        }

        $person_scoreArr = array();
        foreach($person_scoreData as $v){
            if(!isset($person_scoreArr[$v['student_id']][$v['tag']])){
                $person_scoreArr[$v['student_id']][$v['tag']] = array();
            }
            $person_scoreArr[$v['student_id']][$v['tag']][$v['times']] = $v['avg'];
        }

        //拼装数据
        //根据tag来确定有几项
        $temp = array();
        $temp1 = array();
        $stu_temp = array();
        foreach($tagArr as $v){
            $temp1[$v]['name'] = $settingArr[$v]['name'];
            if(!isset($bigCamp_statusArr[$v]['1'])){
                $bigCamp_statusArr[$v]['1'] = 0;
            }
            if(!isset($smallCamp_statusArr[$v]['1'])){
                $smallCamp_statusArr[$v]['1'] = 0;
            }
            //先拼装大营和小营的公共部分
            if($v == 'kaoqin'){
                $temp1[$v]['type'] = '1';
				if(array_sum($bigCamp_statusArr[$v])){
					$temp['big_'.$v] = round($bigCamp_statusArr[$v]['1'] / array_sum($bigCamp_statusArr[$v]) * 100,2);
				}else{
					$temp['big_'.$v] = 0;
				}
				if(array_sum($smallCamp_statusArr[$v])){
					$temp['small_'.$v] = round($smallCamp_statusArr[$v]['1'] / array_sum($smallCamp_statusArr[$v]) * 100,2);
				}else{
					$temp['small_'.$v] = 0;
				}
            }elseif(in_array($v,['test','zuoye','jiaxiao','dictation'])){
                $temp1[$v]['type'] = '3';
				if(array_sum($bigCamp_statusArr[$v])){
					$temp['big_'.$v] = round($bigCamp_statusArr[$v]['1'] / array_sum($bigCamp_statusArr[$v]) * 100,2);
				}else{
					$temp['big_'.$v] = 0;
				}
				if(array_sum($smallCamp_statusArr[$v])){
					$temp['small_'.$v] = round($smallCamp_statusArr[$v]['1'] / array_sum($smallCamp_statusArr[$v]) * 100,2);
				}else{
					$temp['small_'.$v] = 0;
				}
                $temp['big_'.$v.'_score'] = $bigCamp_scoreArr[$v];
                $temp['small_'.$v.'_score'] = $smallCamp_scoreArr[$v];
                if(count($bigCamp_scoreArr[$v]) > 1){
                    $temp1[$v]['multi'] = '1';
                }
				if(count($bigCamp_scoreArr[$v])){
					$temp['big_'.$v.'_avg'] = round(array_sum($bigCamp_scoreArr[$v]) / count($bigCamp_scoreArr[$v]),2);
				}else{
					$temp['big_'.$v.'_avg'] = 0;
				}
				if(count($smallCamp_scoreArr[$v])){
					$temp['small_'.$v.'_avg'] = round(array_sum($smallCamp_scoreArr[$v]) / count($smallCamp_scoreArr[$v]),2);
				}else{
					$temp['small_'.$v.'_avg'] = 0;
				}
            }else{
                $temp1[$v]['status'] = $settingArr[$v]['status_item'];
                if($settingArr[$v]['use_status'] == '1'){
                    $temp['big_'.$v] = round($bigCamp_statusArr[$v]['1'] / array_sum($bigCamp_statusArr[$v]) * 100,2);
                    $temp['small_'.$v] = round($smallCamp_statusArr[$v]['1'] / array_sum($smallCamp_statusArr[$v]) * 100,2);
                    $temp1[$v]['type'] = '1';
                }
                if($settingArr[$v]['score_status'] == '1'){
                    $temp['big_'.$v.'_score'] = $bigCamp_scoreArr[$v];
					if(isset($smallCamp_scoreArr[$v])){
						$smallCamp_scoreArr[$v] = $smallCamp_scoreArr[$v];
					}else{
						$smallCamp_scoreArr[$v] = [0];
					}
					$temp['small_'.$v.'_score'] = $smallCamp_scoreArr[$v];
                    if(count($bigCamp_scoreArr[$v]) > 1){
                        $temp1[$v]['multi'] = '1';
                    }
                    $temp['big_'.$v.'_avg'] = round(array_sum($bigCamp_scoreArr[$v]) / count($bigCamp_scoreArr[$v]),2);
                    $temp['small_'.$v.'_avg'] = round(array_sum($smallCamp_scoreArr[$v]) / count($smallCamp_scoreArr[$v]),2);
                    $temp1[$v]['type'] = '2';
                }
                if($settingArr[$v]['use_status'] == '1' && $settingArr[$v]['score_status'] == '1'){
                    $temp1[$v]['type'] = '3';
                }
            }
        }
        if($is_radar){
            $temp1['radar'] = array();
            $temp1['radar']['name'] = '雷达';
        }

        foreach($temp1 as $_key => $_value){
            $temp1[$_key]['item'] = $_key;
        }

        $temp1 = array_values($temp1);


        $rate_memo = array();
        //每个人的准交率
        foreach($tagArr as $v){
            foreach($person_statusArr as $_k => $_v){
                if(!isset($stu_temp[$_k])){
                    $stu_temp[$_k] = array();
                }
                if(!isset($person_statusArr[$_k][$v]['1'])){
                    $person_statusArr[$_k][$v]['1'] = 0;
                }
				if(array_sum($person_statusArr[$_k][$v])){
					$stu_temp[$_k][$v]['rate'] =  round($person_statusArr[$_k][$v]['1'] / array_sum($person_statusArr[$_k][$v]) * 100,2);
				}else{
					$stu_temp[$_k][$v]['rate'] =  0;
				}
				if(array_sum($person_statusArr[$_k][$v])){
					$rate_memo[$_k][$v] =  round($person_statusArr[$_k][$v]['1'] / array_sum($person_statusArr[$_k][$v]) * 100,2);
				}else{
					$rate_memo[$_k][$v] =  0;
				}

                $rate_memo[$_k]['id'] = $_k;
            }
        }

        foreach($tagArr as $v){
            $rate = array();$tag = 0;
            foreach($rate_memo as $_k => $_v){
                if(!isset($_v[$v])){
                    $tag = 1;
                    break;
                }
                $rate[$_k] = $_v[$v];
            }
            if($tag == 1){
                continue;
            }
            array_multisort($rate,SORT_ASC,$rate_memo);
            $i=1;
            foreach($rate_memo as $_k => $_v){
                if($_v[$v] == 100){
                    $rateNum = 100;
                }else{
                    $rateNum = round($i / count($rate_memo) * 100,2);
                }
                $normalWord = '正常率';
                if($settingArr[$v]['name'] == '考勤'){
                    $normalWord = '全勤率';
                }
                if($big_camp == 'Wonder Museum'){
                    if($settingArr[$v]['name'] == '考勤'){
                        if($_v['kaoqin'] == 100){
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '坚持全勤，为你点赞！博物馆之旅还剩最后一周！你一定能坚持到最后！';
                        }else{
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '有点小遗憾！希望你及时调整，最后一周每天都能准时看到能量满满的你！';
                        }
                    }elseif($settingArr[$v]['name'] == '作业'){
                        if($_v['zuoye'] == 100){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '你有很好的学习习惯，能够按照要求按时自主完成学习任务，真棒为你点赞！';
                        }else{
                            $stu_temp[$_v['id']][$v]['score_memo'] = '希望你能脚踏实地，及时完成自己每天的学习任务并准时上交哦！最后一周加油哇！';
                        }
                    }else{
                        if($rateNum <= 50){
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '你的'.$settingArr[$v]['name'].$normalWord.'超过了'.$rateNum.'%的营内同学，请继续努力';
                        }else{
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '你的'.$settingArr[$v]['name'].$normalWord.'超过了'.$rateNum.'%的营内同学，请继续保持';
                        }
                    }
                }elseif ($big_camp == 'Fantastic Writing') {
                   if($settingArr[$v]['name'] == '考勤'){
                        if($_v['kaoqin'] == 100){
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '坚持全勤，给你点赞👍 期待你每一天都能继续保持😊';
                        }else{
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '这周有点小遗憾哦～🤔虽然没有全勤，但是我们相信你下一次一定可以做到⛽️希望每一天都能和你度过～';
                        }
                    }
                }elseif($big_camp == "Science Festiva"){
					if($v == "kaoqin"){
					    if($_v['kaoqin'] == 100){
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '坚持全勤100%，给你点赞👍  每天叫醒你的那个人是谁呢？别忘记谢谢她／他呀！😉';
                        }else{
                            $stu_temp[$_v['id']][$v]['rate_memo'] = '有点小遗憾哦～🤔没有坚持全勤～';
                        }
					}elseif($v == "zuoye"){
                        if($_v['zuoye'] == 100){
                            $stu_temp[$_v['id']][$v]['rate_memo'] = "你有很好的学习习惯，能够按照要求按时自主完成学习任务，真棒为你点赞！";
                        }else{
                            $stu_temp[$_v['id']][$v]['rate_memo'] = "你有很好的学习习惯，能够按照要求按时自主完成学习任务，真棒为你点赞！";
                        }
                    }else{
						$stu_temp[$_v['id']][$v]['rate_memo'] = "";
					}

					// if($v == "zuoye"){
					// 	$stu_temp[$_v['id']][$v]['rate_memo'] = "test_zuoye";
					// }
					// if($v == "reading_rate"){
					// 	$stu_temp[$_v['id']][$v]['rate_memo'] = "test_reading_rate";
					// }
					// if($v == "reading_speed"){
					// 	$stu_temp[$_v['id']][$v]['rate_memo'] = "test_reading_speed";
					// }
					// if($v == "scanning_skimming"){
					// 	$stu_temp[$_v['id']][$v]['rate_memo'] = "test_scanning_skimming";
					// }
					// if($v == "phonics_rate"){
					// 	$stu_temp[$_v['id']][$v]['rate_memo'] = "test_phonics_rate";
					// }
				}else{
					if($rateNum <= 50){
                        $stu_temp[$_v['id']][$v]['rate_memo'] = '你的'.$settingArr[$v]['name'].$normalWord.'超过了'.$rateNum.'%的营内同学，请继续努力';
                    }else{
                        $stu_temp[$_v['id']][$v]['rate_memo'] = '你的'.$settingArr[$v]['name'].$normalWord.'超过了'.$rateNum.'%的营内同学，请继续保持';
                    }
				}
                $i++;
            }
        }
        $score_memo=array();
        //每个人的分数
        foreach($tagArr as $v){
            if(!isset($smallCamp_scoreArr[$v])){
                continue;
            }
            $key = array_keys($smallCamp_scoreArr[$v]);
            foreach($person_scoreArr as $_k => $_v){
                if(!isset($stu_temp[$_k])){
                    $stu_temp[$_k] = array();
                }
                $stu_temp[$_k]['ch_name'] = $stuArr[$_k]['ch_name'];
                $stu_temp[$_k]['en_name'] = $stuArr[$_k]['en_name'];

                foreach($key as $value){
                    if(!isset($person_scoreArr[$_k][$v][$value])){
                        $person_scoreArr[$_k][$v][$value] = 0;
                    }
                }

                $stu_temp[$_k][$v]['avg'] = round(array_sum($person_scoreArr[$_k][$v]) / count($person_scoreArr[$_k][$v]),2);
                $stu_temp[$_k][$v]['all'] = $person_scoreArr[$_k][$v];
                if($v == 'scanning_skimming'){
                    $score_memo[$_k][$v] = $person_scoreArr[$_k][$v];
                }else{
                    $score_memo[$_k][$v] = round(array_sum($person_scoreArr[$_k][$v]) / count($person_scoreArr[$_k][$v]),2);
                }
                $score_memo[$_k]['id'] = $_k;
            }
        }
        foreach($tagArr as $v){
            $rate = array();$tag = 0;
            foreach($score_memo as $_k => $_v){
                if(!isset($_v[$v])){
                    $tag=1;
                    break;
                }
                $rate[$_k] = $_v[$v];
            }
            if($tag == 1){
                continue;
            }
            array_multisort($rate,SORT_ASC,$score_memo);
            $i=1;
            if($big_camp == "Science Festiva"){
                $sortBy_reading_rate = array_column($score_memo,'reading_rate');
                $sortBy_reading_speed = array_column($score_memo,'reading_speed');
                $totalCount = count($score_memo);
                $reading_rate_sorted_score_memo = $score_memo;
                $reading_speed_sorted_score_memo = $score_memo;
                array_multisort($sortBy_reading_rate,SORT_DESC,$reading_rate_sorted_score_memo);
                array_multisort($sortBy_reading_speed,SORT_DESC,$reading_speed_sorted_score_memo);
            }
            foreach($score_memo as $_k => $_v){
                if($_v[$v] == 100){
                    $rateNum = 100;
                }else{
                    $rateNum = round($i / count($score_memo) * 100,2);
                }
                if($big_camp == 'Wonder Museum'){
                    if($v == 'test'){
						if($_v['test'] == 10){
							$stu_temp[$_v['id']][$v]['score_memo'] = "Excellent！老师真为你感到骄傲！肯定是认真听课和复习，让你如此优秀你有好的学习方法也可以分享给其他小朋友呀～	";
						}elseif($_v['test'] <= 9.9 && $_v['test'] >= 9){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '是不是自己的粗心大意让自己和满分失之交臂？真是太可惜啦！这样一定要总结经验，好好发挥出自己的真实水平，相信你在接下来的学习中一定会越来越棒！';
                        }elseif($_v['test'] < 9.0 && $_v['test'] >= 8.0){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '可以看到你对基础的知识点和内容掌握地还是很牢固的，但是对于综合运用和替换还有一点点小问题。希望你在将来的学习中加强自己的薄弱环节，提高自己综合运用的能力哦~';
                        }elseif($_v['test'] < 8.0 && $_v['test'] >= 6.0){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '是不是由于对知识点的掌握不牢固，没有灵活运用？还是因为没有认真复习，所以导致本次测试成绩没到达到自己的预期呢？希望你及时查缺补漏，调整状态！';
                        }elseif($_v['test'] < 6.0){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '辛苦付出了3个周，你也许需要思考一下自己的学习方式是否高效，对时间的分配是否合理。一定要不断探索最适合自己的学习方式呀！❤';
                        }
                    }

                    if($v == 'zuoye'){
						// if($_v['zuoye'] == 100){
						// 	$stu_temp[$_v['id']][$v]['score_memo'] = "你有很好的学习习惯哦，不丢三落四，能够清楚地知道自己的学习任务，有很好的时间观念，从这样一件小小的事可以折射出你非常端正的学习态度～真棒为你点赞";
						// }else{
						// 	$stu_temp[$_v['id']][$v]['score_memo'] = "😤为什么没有交本次的作业呢？是因为太难还是太简单？希望你能脚踏实地，戒骄戒躁，在及时完成自己的学习任务并准时上交哦～保持积极的学习态度哈～我相信你下一次一定是最棒的那一个！";
						// }
                        // if($_v['zuoye'] <= 100 && $_v['zuoye'] >= 80){
                        //     $stu_temp[$_v['id']][$v]['score_memo'] = $stu_temp[$_v['id']][$v]['rate_memo'] . '每一次都超级认真的完成作业✍️书写清秀认真、每一次的分享都极具特色和创意💡 Elegant ! 谢谢你每次都让我觉得批改作业是一件很享受的事情～我想一直这么享受下去呢～😘';
                        // }elseif($_v['zuoye'] < 80 && $_v['zuoye'] >= 60){
                        //     $stu_temp[$_v['id']][$v]['score_memo'] = $stu_temp[$_v['id']][$v]['rate_memo'] . 'I’m pleased that you have made so great progress now ! Proud of you ! 👏👏👏为你的努力和进步喝彩哦～🍾  我相信在接下来更多的挑战中，努力和认真一定可以为你再次助力的🚀';
                        // }elseif($_v['zuoye'] < 60){
                        //     $stu_temp[$_v['id']][$v]['score_memo'] = $stu_temp[$_v['id']][$v]['rate_memo'] . '好极了！尽管还有一些小的地方需要改进，但和自己比，你已经在慢慢进步咯👍但是你的字“伸胳膊缩腿”呀～请你管管它哦～请让它规规矩矩，方方正正！⛽️Wonderful in spirt of a few mistakes ! You have made a progress now! ';
                        // }
                    }

					//阅读
                    if($v == 'reading'){
                        if($_v['reading'] >= 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = ' 你就是传说中的“阅读之星”！希望在保持流利阅读的基础上也能更快地掌握文本内容哦！';
                        }elseif($_v['reading'] < 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '你已经有了很大进步！希望你再接再厉，在将来不断突破自己！';
                        }
                    }
					//单词
                    if($v == 'words'){
                        if($_v['words'] >= 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '你就是传说中的“万词王”！在不断学习新单词的同时也不要忘记对这3周单词进行回顾～';
                        }elseif($_v['words'] < 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '看来对于咱们所学词汇掌握的不是很好，希望你利用好零碎时间，提高自己的学习效率。';
                        }
                    }
					//语法
                    if($v == 'grammar'){
                        if($_v['grammar'] >= 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '你就是传说中的“法海”！恭喜你本3周成功掌握语法知识点。希望你开学来继续脚踏实地，勇往直前～期待你更好的表现！';
                        }elseif($_v['grammar'] < 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '最后一周一定要更认真努力，踏踏实实地完成每天的语法作业，如果有不清楚的及时向老师进行询问！';
                        }
                    }
					//自然拼读
					if($v == 'phonics'){
                        if($_v['phonics'] >= 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = 'Excellent！👍 你就是传说中的“拼读之王”吧！恭喜你拿下了3周的拼读堡垒，成功通关，希望你开学继续脚踏实地，勇往直前哟～期待你更好的表现呀！';
                        }elseif($_v['phonics'] < 6){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '💔3周的自然拼读词汇对你来说是不是没有掌握？希望你3周一定要努力提升自己的课堂吸收率呀，有不会的一定及时问老师哦💪加油⛽️';
                        }
                    }
                }
                else if ($big_camp == 'Fantastic Writing') {
                    if($v == 'test'){
                        if($_v['test'] <= 100 && $_v['test'] >= 90){
                            $stu_temp[$_v['id']][$v]['score_memo'] = 'Excellent！老师真为你感到骄傲！肯定是认真听课和复习，让你如此优秀你有好的学习方法也可以分享给其他小朋友呀～';
                        }elseif($_v['test'] < 90 && $_v['test'] >= 80){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '可以看出你对3周基础知识掌握的很好，如果有难懂的知识点可以询问老师哦～多一点细致，多一点提问，多一点认真会有不一样的收获哟，加油💪';
                        }elseif($_v['test'] < 80 && $_v['test'] >= 60){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '是不是3周学的知识有点难呢，还是复习有点困难🤔️？我们看到你已经在努力了，有好的学习和复习方法肯定会让你的学习效果事半功倍哦💪';
                        }elseif($_v['test'] < 60){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '宝贝你的成绩是否和你的付出成正比呢？如果3周学习的知识点比较多，或者对你有点难，一定要来询问老师获得帮助哦～及时的复习和适合你自己的学习方法肯定会让你进步的，加油哦⛽️💪';
                        }
                    }

                    if($v == 'zuoye'){
                        if($_v['zuoye'] <= 100 && $_v['zuoye'] >= 80){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '是什么让你的作业完成的那么认真，书写正确又美观✍️？是对写作学习的热爱，认真的态度，还是好的习惯🤔️每次看你的作业都非常开心～为优秀认真的你点赞😘👍';
                        }elseif($_v['zuoye'] < 80 && $_v['zuoye'] >= 60){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '我们看到了你的努力和付出哦～我相信你之后肯定可以越写越好，越写越棒，加油⛽️';
                        }elseif($_v['zuoye'] < 60){
                            $stu_temp[$_v['id']][$v]['score_memo'] = 'Good job～尽管还有一些小的地方需要改进，但和自己比，你已经在慢慢进步咯👍期待下次看到你的字端端正正，清清秀秀～';
                        }
                    }
                    if($v == 'dictation'){
                        if($_v['dictation'] <= 100 && $_v['dictation'] >= 90){
                            $stu_temp[$_v['id']][$v]['score_memo'] = 'Excellent！👍 你就是传说中的“万词王”吧！一篇好文章离不开丰富的词汇积累，有了词汇的法宝肯定能帮助你写地更好这一周，为你骄傲💪';
                        }elseif($_v['dictation'] < 90 && $_v['dictation'] >= 80){
                            $stu_temp[$_v['id']][$v]['score_memo'] = 'Good job！相信你可以掌握更多词汇，我己经看到你的努力和进步了，再接再厉⛽️';
                        }elseif($_v['dictation'] < 80 && $_v['dictation'] >= 70){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '💔这周是不是有点粗心呢～我们开学一起再接再厉好吗💪每天一点点努力和认真会有不一样的收获哦❤️';
                        }elseif($_v['dictation'] >= 60 && $_v['dictation'] < 70){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '💔看来对于3周所学词汇掌握的不是很好哦，希望你每天利用好时间，花点时间来记单词，💯也不是很难嘛，加油呀⛽️';
                        }elseif($_v['dictation'] < 60){
                            $stu_temp[$_v['id']][$v]['score_memo'] = '💔3周的词汇对你来说是不是有一点难记忆？如果是，那么现在更要认真，努力吸收每堂课的知识哦～如果有不会的，老师就在你身边可以随时帮助你～每天进步一点点马上就可以看到效果～加油，你会越来越棒⛽️';
                        }
                    }
				}
				elseif($big_camp == "Science Festiva"){
                    // if($v == "zuoye"){
                    //     if($_v['zuoye'] == 100){
                    //         $stu_temp[$_v['id']][$v]['score_memo'] = "abcdef";
                    //     }else{
                    //         $stu_temp[$_v['id']][$v]['score_memo'] = "fedcba";
                    //     }
                    // }
					if($camp_id >= 27 && $camp_id<= 35) {
						if($v == "reading_rate"){
                            foreach($reading_rate_sorted_score_memo as $kkk => $rrr){
                                if($_v['reading_rate'] >= $rrr['reading_rate']){
                                    $score_memo[$_k]['reading_rate_rankRate'] = (1 - ($kkk + 1) / $totalCount) * 100;
                                    break;
                                }
                            }
							if($score_memo[$_k]['reading_rate_rankRate'] > 75){
								$stu_temp[$_v['id']][$v]['score_memo'] = "Excellent！👍 你就是传说中的“阅读之星”吧！速度这么快！正确率这么高！👏在3周苦令营期间，你越来越像一名合格的科学家👩‍🔬👨‍🔬了，拥有可贵的阅读精神，富足的知识储备，为你自豪💪";
							}
							if($score_memo[$_k]['reading_rate_rankRate'] <= 75 && $score_memo[$_k]['reading_rate_rankRate'] > 50){
								$stu_temp[$_v['id']][$v]['score_memo'] = "好极了！尽管速度还可以更快，正确率还可以更高，但和自己比，你已经在慢慢进步咯👍⛽️为你的努力和进步喝彩哦～🍾  我相信在接下来更多的挑战中，努力和认真一定可以为你再次助力的🚀";
							}
							if($score_memo[$_k]['reading_rate_rankRate'] <= 50 && $score_memo[$_k]['reading_rate_rankRate'] > 25){
								$stu_temp[$_v['id']][$v]['score_memo'] = "💔3周的文章和话题对你来说是不是有一点点难理解？如果是，那么现在更要认真，努力吸收每堂课的知识，回家花时间去练习哦～如果有不会的，一定要及时的询问老师哦！补足自己的短板，每天进步一点点哟～加油，你会越来越棒⛽️";
							}
							if($score_memo[$_k]['reading_rate_rankRate'] <= 25){
								$stu_temp[$_v['id']][$v]['score_memo'] = "💔看来对于咱们所学的词汇和文章话题掌握的不是很好哦，希望你每天利用好零碎时间，腾出时间来【读书】，一步一步稳扎稳打～努力修炼哈";
							}
						}
						if($v == "reading_speed"){
                            foreach($reading_speed_sorted_score_memo as $kkk => $rrr){
                                if($_v['reading_speed'] >= $rrr['reading_speed']){
                                    $score_memo[$_k]['reading_speed_rankRate'] = (1 - ($kkk + 1) / $totalCount) * 100;
                                    break;
                                }
                            }
							if($score_memo[$_k]['reading_speed_rankRate'] > 75){
								$stu_temp[$_v['id']][$v]['score_memo'] = "Excellent！👍 你就是传说中的“阅读之星”吧！速度这么快！正确率这么高！👏在3周苦令营期间，你越来越像一名合格的科学家👩‍🔬👨‍🔬了，拥有可贵的阅读精神，富足的知识储备，为你自豪💪";
							}
							if($score_memo[$_k]['reading_speed_rankRate'] <= 75 && $score_memo[$_k]['reading_speed_rankRate'] > 50){
								$stu_temp[$_v['id']][$v]['score_memo'] = "好极了！尽管速度还可以更快，正确率还可以更高，但和自己比，你已经在慢慢进步咯👍⛽️为你的努力和进步喝彩哦～🍾  我相信在接下来更多的挑战中，努力和认真一定可以为你再次助力的🚀";
							}
							if($score_memo[$_k]['reading_speed_rankRate'] <= 50 && $score_memo[$_k]['reading_speed_rankRate'] > 25){
								$stu_temp[$_v['id']][$v]['score_memo'] = "💔3周的文章和话题对你来说是不是有一点点难理解？如果是，那么现在更要认真，努力吸收每堂课的知识，回家花时间去练习哦～如果有不会的，一定要及时的询问老师哦！补足自己的短板，每天进步一点点哟～加油，你会越来越棒⛽️";
							}
							if($score_memo[$_k]['reading_speed_rankRate'] <= 25){
								$stu_temp[$_v['id']][$v]['score_memo'] = "💔看来对于咱们所学的词汇和文章话题掌握的不是很好哦，希望你每天利用好零碎时间，腾出时间来【读书】，一步一步稳扎稳打～努力修炼哈";
							}
						}
						if($v == "scanning_skimming"){
							// $stu_temp[$_v['id']][$v]['score_memo'] = "test_scanning_skimming";
							if(array_last($_v['scanning_skimming']) == 100){
								$stu_temp[$_v['id']][$v]['score_memo'] = "是什么让你能把所有的阅读理解题都做正确了呢👍👍？是对阅读的热爱，认真的态度，上课的专注，还是好的习惯🤔️每次看你的表现都非常开心～为优秀认真的你点赞😘👍";
							}
							if(array_last($_v['scanning_skimming']) == 80){
								$stu_temp[$_v['id']][$v]['score_memo'] = "哎呀，是不是自己的粗心大意让自己和💯失之交臂呀，真是太可惜啦，这样一定要总结经验，争取下次避开所有的雷区，不掉到坑里去，好好发挥出自己的真实水平呀，真是为你自豪，相信你在接下来的学习中一定会越来越棒！⛽️如果你有更多更棒更好的学习方法和技巧，也欢迎你积极分享给我们营的小朋友哦～💪";
							}
							if(array_last($_v['scanning_skimming']) == 60){
								$stu_temp[$_v['id']][$v]['score_memo'] = "可以看到你对基础的知识点和内容掌握地还是很牢固的，但是对于综合运用和阅读理解还有一点点小问题，希望你在平时的日常练习中，能够有意识地加强自己的薄弱环节，通过阅读各类文章,弄清题意,深入思考,不断探索,做到答题准确,有理有据,从而逐步找到了提高阅读能力的门径，提高自己综合运用的能力哦~继续加油，我相信你会越来越棒的💪";
							}
							if(array_last($_v['scanning_skimming']) == 40){
								$stu_temp[$_v['id']][$v]['score_memo'] = "是不是由于对知识点的掌握不牢固，没有做好活学活用？还是因为没有认真复习，所以导致本次测试成绩没到达到自己的预期呢？希望你在日常学习中稳扎稳打，通过阅读各类文章,弄清题意,深入思考,不断探索,做到答题准确,有理有据,从而逐步找到了提高阅读能力的门径，提高自己综合运用的能力。如果有不会的，一定要及时的询问老师哦～下次考试中能够发挥出色，为自己交上一份漂亮的答卷哟⛽️";
							}
							if(array_last($_v['scanning_skimming']) == 20){
								$stu_temp[$_v['id']][$v]['score_memo'] = "手中拿到的测试成绩是否与你平时的努力付出成正比呢？如果不是，那么你需要思考一下自己的学习方式是否高效，对时间的分配是否合理。一定要不断探索最适合自己的学习方式，通过阅读各类文章,弄清题意,深入思考,不断探索,做到答题准确,有理有据,从而逐步找到了提高阅读能力的门径，提高自己综合运用的能力哦。加油呀～To be a better you！❤️";
							}
                            if(array_last($_v['scanning_skimming']) == 0){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "你没有参加本次测试哦，是为什么呢，开学不可以这样了";
                            }
						}
						// if($v == "phonics_rate"){
						// 	$stu_temp[$_v['id']][$v]['score_memo'] = "test_phonics_rate";
						// }
					}
					elseif($camp_id >= 36 && $camp_id<= 40) {
                        if($v == "phonics_rate"){
                            if($_v['phonics_rate'] > 25){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "Bravo !!!👍 你一定是我们的拼读小达人！ 很棒🌟
在3周苦令营期间为新知识做好准备了吗？ Let’s go!!!💪💪💪";
                            }
                            if($_v['phonics_rate'] <= 25 && $_v['phonics_rate'] >= 20){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "太棒了，相信你对于自然拼读已经掌握的很不错了！突破自己的速度你就会成为最棒的！加油！👍";
                            }
                            if($_v['phonics_rate'] <= 19 && $_v['phonics_rate'] >= 10){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "看来可能3周所学习的自然拼读规律还有部分需要去查缺补漏的，记得每天都跟着音频一起练习呢！ 只要多多练习，一定可以会更棒的！相信自己！⛽️⛽️⛽️";
                            }
                            if($_v['phonics_rate'] <= 10){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "对于所学习的自然拼读规律大部分的知识应该都没有吸收，是不是课堂没有大声的，专心的学习呢？还是回家没有很好的练习巩固呢？赶紧调整一下哦，加油哦。";
                            }
                        }
                        if($v == "letter_rate"){
                            if((double)$_v['letter_rate'] > 11){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "是不是我们的phonics song 已经让你难以忘记了呢👍👍？上课认真听，大声练习，回家踏踏实实复习的你值的满分💯💪接下来的两个星期希望你继续加油，保持哦！😄";
                            }
                            if((double)$_v['letter_rate'] <= 11 && (double)$_v['letter_rate'] >= 9){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "一不小心就和💯满分失之交臂，没关系的！下次可以再尝试，为你在课堂上积极的表现骄傲！💪";
                            }
                            if((double)$_v['letter_rate'] <= 8 && (double)$_v['letter_rate'] >= 6){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "可以看出对于自然拼读大部分的字母发音还是掌握了👍但是是不是我们唱了很多遍的phonics song还没有让你睡着都唱着呢😬 是不是歌曲的耨一部分还不是特别熟悉呢？ 可以多多练习几遍，你一定可以的！👍";
                            }
                            if((double)$_v['letter_rate'] <= 5){
                                $stu_temp[$_v['id']]['letter_rate']['score_memo'] = "成绩是否和你的付出成正比了？ 是不是方法没有选择对呢？ ☹️对于基本的字母音一定要多听，这样你才能够记住哦。 字母音是我们自然拼读学习的最基础，所以要加油了哦。 如果是因为小偷懒的话， 接下来的学习中要加油了哦。💪这样你就能快快的跟上我们学习的大部队了哦，加油！ 你一定可以的。😃";
                            }
                        }
                        if($v == "scanning_skimming"){
                            // $stu_temp[$_v['id']][$v]['score_memo'] = "test_scanning_skimming";
                            if($_v['scanning_skimming'] == 100){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "是什么让你能把所有的阅读理解题都做正确了呢？是对阅读的热爱，认真的态度，上课的专注，还是好的习惯🤔️每次看你的表现都非常开心～为优秀认真的你点赞";
                            }
                            if($_v['scanning_skimming'] == 80){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "哎呀，是不是自己的粗心大意让自己和💯失之交臂呀，真是太可惜啦，这样一定要总结经验，争取下次避开所有的雷区，不掉到坑里去，好好发挥出自己的真实水平呀，真是为你自豪，相信你在接下来的学习中一定会越来越棒！️如果你有更多更棒更好的学习方法和技巧，也欢迎你积极分享给我们营的小朋友哦～";
                            }
                            if($_v['scanning_skimming'] == 60){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "可以看到你对基础的知识点和内容掌握地还是很牢固的，但是对于综合运用和阅读理解还有一点点小问题，希望你在平时的日常练习中，能够有意识地加强自己的薄弱环节，通过阅读各类文章,弄清题意,深入思考,不断探索,做到答题准确,有理有据,从而逐步找到了提高阅读能力的门径，提高自己综合运用的能力哦~继续加油，我相信你会越来越棒的";
                            }
                            if($_v['scanning_skimming'] == 40){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "是不是由于对知识点的掌握不牢固，没有做好活学活用？还是因为没有认真复习，所以导致本次测试成绩没到达到自己的预期呢？希望你在日常学习中稳扎稳打，通过阅读各类文章,弄清题意,深入思考,不断探索,做到答题准确,有理有据,从而逐步找到了提高阅读能力的门径，提高自己综合运用的能力。如果有不会的，一定要及时的询问老师哦～下次考试中能够发挥出色，为自己交上一份漂亮的答卷哟️";
                            }
                            if($_v['scanning_skimming'] == 20){
                                $stu_temp[$_v['id']][$v]['score_memo'] = "手中拿到的测试成绩是否与你平时的努力付出成正比呢？如果不是，那么你需要思考一下自己的学习方式是否高效，对时间的分配是否合理。一定要不断探索最适合自己的学习方式，通过阅读各类文章,弄清题意,深入思考,不断探索,做到答题准确,有理有据,从而逐步找到了提高阅读能力的门径，提高自己综合运用的能力哦。加油呀～To be a better you！️";
                            }
                        }
						if($v == "reading_rate"){
							if($rateNum > 75){
								$stu_temp[$_v['id']][$v]['score_memo'] = "Excellent！👍 你就是传说中的“阅读之星”吧！速度这么快！正确率这么高！👏在3周苦令营期间，你越来越像一名合格的科学家👩‍🔬👨‍🔬了，拥有可贵的阅读精神，富足的知识储备，为你自豪💪";
							}
							if($rateNum <= 75 && $rateNum > 50){
								$stu_temp[$_v['id']][$v]['score_memo'] = "好极了！尽管速度还可以更快，正确率还可以更高，但和自己比，你已经在慢慢进步咯👍⛽️为你的努力和进步喝彩哦～🍾  我相信在接下来更多的挑战中，努力和认真一定可以为你再次助力的🚀";
							}
							if($rateNum <= 50 && $rateNum > 25){
								$stu_temp[$_v['id']][$v]['score_memo'] = "💔3周的文章和话题对你来说是不是有一点点难理解？如果是，那么现在更要认真，努力吸收每堂课的知识，回家花时间去练习哦～如果有不会的，一定要及时的询问老师哦！补足自己的短板，每天进步一点点哟～加油，你会越来越棒⛽️";
							}
							if($rateNum <= 25){
								$stu_temp[$_v['id']][$v]['score_memo'] = "💔看来对于咱们所学的词汇和文章话题掌握的不是很好哦，希望你每天利用好零碎时间，腾出时间来【读书】，一步一步稳扎稳打～努力修炼哈";
							}
						}
					}
				}
				else{
					if($rateNum <= 50){
                        $stu_temp[$_v['id']][$v]['score_memo'] = '你的'.$settingArr[$v]['name'].'分数超过了'.$rateNum.'%的营内同学，请继续努力';
                    }else{
                        $stu_temp[$_v['id']][$v]['score_memo'] = '你的'.$settingArr[$v]['name'].'分数超过了'.$rateNum.'%的营内同学，请继续保持';
                    }
				}
				$i++;
			}
        }
		if($camp_id >= 27 && $camp_id<= 35) {
			unset($temp1[5]);
			$color['image'] = ["#DCD235","#1E4098","#2CA6E0"];
			$color['image_display'] = $color['text'] = $color["axis"] = "#9C9EA0";
			$color['split'] = "#f2f2f3";
		}
		if($camp_id >= 36 && $camp_id<= 40) {
			unset($temp1[0]);
			$color['image'] = ["#DCD235","#1E4098","#2CA6E0"];
			$color['image_display'] = $color['text'] = $color["axis"] = "#9C9EA0";
			$color['split'] = "#f2f2f3";
		}
        if($camp_id >= 41 && $camp_id<= 49) {
            unset($temp1[5]);
        }
        if($camp_id >= 50 && $camp_id<= 57) {
            unset($temp1[2]);
        }

        return array('common'=>$temp,'item'=>$temp1,'student'=>$stu_temp,'tutor'=>array_first($tutor),'camp_name'=>$camp_name,'camp'=>$bigcamp_setting[0],'memo'=>$memo,'color'=>$color,'big_camp'=>$big_camp,'date'=>$time_arr);
    }

    public function report_detail(Content $content,Request $request)
    {
        $content->header(' ');
        $content->description(' ');
		$report = Kly_report::find($request['pid']);
        $camp_id = $report->small_camp;
        $camp_pid = Kly_camp::find($camp_id)->pid;
        $big_camp = Kly_camp::find($camp_pid)->name;
		$big_camp = preg_replace('# #','',$big_camp);
		$blade = 'admin.kly.report.'.$big_camp;
		if($big_camp == "ScienceFestiva"){
			if($camp_id >= 27 && $camp_id<= 35) {
				$blade .= "0";
			}
			if($camp_id >= 36 && $camp_id<= 40) {
				$blade .= "1";
			}
		}
		if($big_camp == "WonderMuseum"){
			if($camp_id >= 41 && $camp_id<= 49) {
				$blade .= "0";
			}
			if($camp_id >= 50 && $camp_id<= 57) {
				$blade .= "1";
			}
		}
        $content->row(view($blade)->with('id',$request['id']));
        return $content;

    }

    public function save_memo(Request $request)
    {
        $memo = $request['memo'];
        $id = $request['pid'];

        DB::table('kly_reports')->where('id',$id)->update(['memo'=>$memo]);

        return array('status'=>1);
    }

    public function report_export(Request $request)
    {
        return view('admin.kly.report_export');
    }

    public function student_get(Request $request)
    {
        $stu = DB::table('kly_reports as kr')->join('kly_students as ks','ks.small_camp_id','=','kr.small_camp')
            ->get(['ks.student_id']);

        $stuArr = array();
        foreach($stu as $v){
            $stuArr[] = $v->student_id;
        }

        return $stuArr;
    }

    public function speak_report(Content $content)
    {
        $content->header('报表详情');
        $content->description('详情');

        $big = Kly_camp::where('name','Speak Great')->value('id');
        $small = Kly_camp::where('pid',$big)->pluck('name','id');
        $content->row(view('admin.kly.speak_report',compact('small')));
        return $content;
    }

    public function speak_report_submit(Request $request)
    {
        $startD = "2019-07-28 00:00:00";

        $start = date('Y-m-d 00:00:00',strtotime($startD.'+'.$request['day'].' days'));
        $end = date('Y-m-d 23:59:59',strtotime($startD.'+'.$request['day'].' days'));

        $tag = 0;

        $reading = $words = $zuoye = array();
        $total = $avg = array();
        $temp_total = array();

        $word = $work = array();

        $temp1 = $temp2 = array();
        if($request['type'] == 1){
            //个人
            $notice = DB::table('kly_notice')->whereIn('status',['2','4'])->whereRaw('UNIX_TIMESTAMP(starttime) <='.strtotime($end))
                ->whereRaw('UNIX_TIMESTAMP(starttime) >='.strtotime($start))->where('camp_id',$request['camp'])->get();

            $noticeArr = array();
            $noticeArr['writing_exam'] = array();
            $noticeArr['words_exam'] = array();
            $noticeArr['zuoye'] = array();
            foreach($notice as $v){
                if($v->tag == 'writing_exam'){
                    $noticeArr['writing_exam'][] = $v->id;
                }elseif($v->tag == 'words_exam'){
                    $noticeArr['words_exam'][] = $v->id;
                }elseif($v->tag == 'zuoye'){
                    $noticeArr['zuoye'][] = $v->id;
                }
            }


            $zuoye_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                ->whereIn('kr.notice_id',$noticeArr['zuoye'])->orderBy('kr.score','asc')
                ->get(['s.en_name','kr.score','kr.student_id']);
            $reading_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                ->whereIn('kr.notice_id',$noticeArr['writing_exam'])->orderBy('kr.score','asc')
                ->get(['s.en_name','kr.score','kr.student_id']);
            foreach($zuoye_data as $v){
                $zuoye['name'][] = $v->en_name;
                $zuoye['score'][] = $v->score;
                $temp2[$v->student_id] = $v->score;
            }
            foreach($reading_data as $v){
                $reading['name'][] = $v->en_name;
                $reading['score'][] = $v->score;
            }

            $words_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                ->whereIn('kr.notice_id',$noticeArr['words_exam'])->orderBy('kr.score','asc')
                ->get(['s.en_name','kr.score','kr.student_id']);

            foreach($words_data as $v){
                $words['name'][] = $v->en_name;
                $words['score'][] = $v->score;
                $temp1[$v->student_id] = $v->score;
            }

            if($request['day'] >= 2){
                $startD = "2019-07-28 00:00:00";
                $day = $request['day'] - 1;

                if(date('w',strtotime($startD.'+'.$day.' days')) == 0){
                    $day = $day - 1;
                }

                $start = date('Y-m-d 00:00:00',strtotime($startD.'+'.$day.' days'));
                $end = date('Y-m-d 23:59:59',strtotime($startD.'+'.$day.' days'));
                $Second_notice = DB::table('kly_notice')->whereIn('status',['2','4'])->whereRaw('UNIX_TIMESTAMP(starttime) <='.strtotime($end))
                    ->whereRaw('UNIX_TIMESTAMP(starttime) >='.strtotime($start))->where('camp_id',$request['camp'])->get();

                $Second_noticeArr = array();
                $Second_noticeArr['writing_exam'] = array();
                $Second_noticeArr['words_exam'] = array();
                $Second_noticeArr['zuoye'] = array();
                foreach($Second_notice as $v){
                    if($v->tag == 'writing_exam'){
                        $Second_noticeArr['writing_exam'][] = $v->id;
                    }elseif($v->tag == 'words_exam'){
                        $Second_noticeArr['words_exam'][] = $v->id;
                    }elseif($v->tag == 'zuoye'){
                        $Second_noticeArr['zuoye'][] = $v->id;
                    }
                }

                $Second_zuoye_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->whereIn('kr.notice_id',$Second_noticeArr['zuoye'])->orderBy('kr.score','asc')
                    ->get(['s.en_name','kr.score','kr.student_id']);

                $Second_reading_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->whereIn('kr.notice_id',$Second_noticeArr['writing_exam'])->orderBy('kr.score','asc')
                    ->get(['s.en_name','kr.score','kr.student_id']);
                foreach($zuoye_data as $v){
                    if(!isset($total[$v->student_id])){
                        $total[$v->student_id] = array();
                        $total[$v->student_id]['name'] = '';
                        $total[$v->student_id]['score'] = 0;
                    }
                    $total[$v->student_id]['score']+=$v->score;
                    $total[$v->student_id]['name'] = $v->en_name;
                }
                foreach($reading_data as $v){
                    if(!isset($total[$v->student_id])){
                        $total[$v->student_id] = array();
                        $total[$v->student_id]['name'] = '';
                        $total[$v->student_id]['score'] = 0;
                    }
                    $total[$v->student_id]['score']+=$v->score;
                    $total[$v->student_id]['name'] = $v->en_name;
                }

                $Second_words_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->whereIn('kr.notice_id',$Second_noticeArr['words_exam'])->orderBy('kr.score','asc')
                    ->get(['s.en_name','kr.score','kr.student_id']);
                foreach($words_data as $v){
                    if(!isset($total[$v->student_id])){
                        $total[$v->student_id] = array();
                        $total[$v->student_id]['name'] = '';
                        $total[$v->student_id]['score'] = 0;
                    }
                    $total[$v->student_id]['score']+=$v->score;
                    $total[$v->student_id]['name'] = $v->en_name;
                }
                $temp_total = $total;
                $total = $this->total_sort($total);
            }

            if($request['day'] >= 3){
                if(count($temp2) > 0){
                    foreach($Second_zuoye_data as $v){
                        $work[$v->student_id]['name'] = $v->en_name;
                        $work[$v->student_id]['score'] = $temp2[$v->student_id] - $v->score;
                    }
                    $work = $this->total_sort($work);
                }
                if(count($temp1) > 0){
                    foreach($Second_words_data as $v){
                        $word[$v->student_id]['name'] = $v->en_name;
                        $word[$v->student_id]['score'] = $temp1[$v->student_id] - $v->score;
                    }
                    $word = $this->total_sort($word);
                }
            }
        }elseif($request['type'] == 2){
            //小组

            $group_student = DB::table('kly_students')->where('small_camp_id',$request['camp'])->get();
            $group_stuArr = array();
            foreach($group_student as $v){
                if(!isset($group_stuArr[$v->camp_group_id])){
                    $group_stuArr[$v->camp_group_id] = array();
                }
                $group_stuArr[$v->camp_group_id][] = $v->student_id;
            }

            $group = DB::table('kly_camps')->where('pid',$request['camp'])->pluck('name','id');
            $notice = DB::table('kly_notice')->whereIn('status',['2','4'])->whereRaw('UNIX_TIMESTAMP(starttime) <='.strtotime($end))
                ->whereRaw('UNIX_TIMESTAMP(starttime) >='.strtotime($start))->where('camp_id',$request['camp'])->get();

            $noticeArr = array();
            $noticeArr['writing_exam'] = array();
            $noticeArr['words_exam'] = array();
            $noticeArr['zuoye'] = array();
            foreach($notice as $v){
                if($v->tag == 'writing_exam'){
                    $noticeArr['writing_exam'][] = $v->id;
                }elseif($v->tag == 'words_exam'){
                    $noticeArr['words_exam'][] = $v->id;
                }elseif($v->tag == 'zuoye'){
                    $noticeArr['zuoye'][] = $v->id;
                }
            }

            if($tag == 0){
                //只有词汇
                $zuoye_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->whereIn('kr.notice_id',$noticeArr['zuoye'])
                    ->get(['kr.student_id','kr.score']);
                $reading_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->whereIn('kr.notice_id',$noticeArr['writing_exam'])
                    ->get(['kr.student_id','kr.score']);

                $temp = array();
                foreach($zuoye_data as $v){
                    foreach($group_stuArr as $key=>$value){
                        if(in_array($v->student_id,$value)){
                            if(!isset($temp[$key])){
                                $temp[$key] = array();
                                $temp[$key]['score'] = 0;
                                $temp[$key]['num'] = 0;
                            }
                            $temp[$key]['score'] += $v->score;
                            $temp[$key]['num'] += 1;
                        }
                    }
                }
                $this->temp_sort($temp);
                foreach($temp as $key => $value){
                    if($key == 0){
                        continue;
                    }
                    $zuoye['name'][] = $group[$key];
                    $zuoye['score'][] = $value;
                }


                $temp = array();
                foreach($reading_data as $v){
                    foreach($group_stuArr as $key=>$value){
                        if(in_array($v->student_id,$value)){
                            if(!isset($temp[$key])){
                                $temp[$key] = array();
                                $temp[$key]['score'] = 0;
                                $temp[$key]['num'] = 0;
                            }
                            $temp[$key]['score'] += $v->score;
                            $temp[$key]['num'] += 1;
                        }
                    }
                }
                $this->temp_sort($temp);
                foreach($temp as $key => $value){
                    if($key == 0){
                        continue;
                    }
                    $reading['name'][] = $group[$key];
                    $reading['score'][] = $value;
                }


            }

            $words_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                ->whereIn('kr.notice_id',$noticeArr['words_exam'])
                ->get(['kr.student_id','kr.score']);

            $temp = array();
            foreach($words_data as $v){
                foreach($group_stuArr as $key=>$value){
                    if(in_array($v->student_id,$value)){
                        if(!isset($temp[$key])){
                            $temp[$key] = array();
                            $temp[$key]['score'] = 0;
                            $temp[$key]['num'] = 0;
                        }
                        $temp[$key]['score'] += $v->score;
                        $temp[$key]['num'] += 1;
                    }
                }
            }
            $this->temp_sort($temp);
            foreach($temp as $key => $value){
                if($key == 0){
                    continue;
                }
                $words['name'][] = $group[$key];
                $words['score'][] = $value;
            }
        }elseif($request['type'] == 3){
            $big = Kly_camp::where('name','Speak Great')->value('id');
            $small = Kly_camp::where('pid',$big)->pluck('id');


            $notice = DB::table('kly_notice')->whereIn('status',['2','4'])->whereRaw('UNIX_TIMESTAMP(starttime) <='.strtotime($end))
                ->whereRaw('UNIX_TIMESTAMP(starttime) >='.strtotime($start))->whereIn('camp_id',$small)->get();

            $noticeArr = array();
            $noticeArr['writing_exam'] = array();
            $noticeArr['words_exam'] = array();
            $noticeArr['zuoye'] = array();
            foreach($notice as $v){
                if($v->tag == 'writing_exam'){
                    $noticeArr['writing_exam'][] = $v->id;
                }elseif($v->tag == 'words_exam'){
                    $noticeArr['words_exam'][] = $v->id;
                }elseif($v->tag == 'zuoye'){
                    $noticeArr['zuoye'][] = $v->id;
                }
            }

            if($tag == 0){
                $temp = array();
                $reading_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->join('kly_notice as n','kr.notice_id','=','n.id')
                    ->where('kr.score','>=',0)
                    ->whereIn('kr.notice_id',$noticeArr['writing_exam'])->groupBy('n.camp_id')
                    ->select(DB::raw('round(avg(kr.score)) as avg'),'n.camp_id')->get();
                foreach($reading_data as $v){
                    $temp[$v->camp_id] = $v->avg;
                }
                asort($temp);
                foreach($temp as $k=>$v){
                    $reading['name'][] = Kly_camp::find($k)->name;
                    $reading['score'][] = $v;
                }

                $temp = array();
                $zuoye_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                    ->join('kly_notice as n','kr.notice_id','=','n.id')
                    ->where('kr.score','>=',0)
                    ->whereIn('kr.notice_id',$noticeArr['zuoye'])->groupBy('n.camp_id')
                    ->select(DB::raw('round(avg(kr.score)) as avg'),'n.camp_id')->get();
                foreach($zuoye_data as $v){
                    $temp[$v->camp_id] = $v->avg;
                }
                asort($temp);
                foreach($temp as $k=>$v){
                    $zuoye['name'][] = Kly_camp::find($k)->name;
                    $zuoye['score'][] = $v;
                }
            }

            $temp = array();
            $words_data = DB::table('kly_records as kr')->join('students as s','kr.student_id','=','s.id')
                ->join('kly_notice as n','kr.notice_id','=','n.id')
                ->where('kr.score','>=',0)
                ->whereIn('kr.notice_id',$noticeArr['words_exam'])->groupBy('n.camp_id')
                ->select(DB::raw('round(avg(kr.score)) as avg'),'n.camp_id')->get();
            foreach($words_data as $v){
                $temp[$v->camp_id] = $v->avg;
            }
            asort($temp);
            foreach($temp as $k=>$v){
                $words['name'][] = Kly_camp::find($k)->name;
                $words['score'][] = $v;
            }
        }
        $count = $num = 0;
        if(isset($reading['score']) && count($reading['score']) > 0){
            foreach($reading['score'] as $v){
                if($v > 0){
                    $count += $v;
                    $num++;
                }
            }
            if($num == 0){
                $reading['avg'] = 0;
            }else{
                $reading['avg'] = round($count / $num,2);
            }
        }


        $count = $num = 0;
        if(isset($words['score']) && count($words['score']) > 0){
            foreach($words['score'] as $v){
                if($v > 0){
                    $count += $v;
                    $num++;
                }
            }
            if($num == 0){
                $words['avg'] = 0;
            }else{
                $words['avg'] = round($count / $num,2);
            }
        }

        $count = $num = 0;
        if(isset($zuoye['score']) && count($zuoye['score']) > 0){
            foreach($zuoye['score'] as $v){
                if($v > 0){
                    $count += $v;
                    $num++;
                }
            }
            if($num == 0){
                $zuoye['avg'] = 0;
            }else{
                $zuoye['avg'] = round($count / $num,2);
            }
        }
        return array('reading'=>$reading,'words'=>$words,'zuoye'=>$zuoye,'total'=>$total,'work'=>$work,'word'=>$word);
    }

    public function temp_sort(&$temp)
    {
        $a = $temp;

        foreach($a as $k => $v){
            if($v['num'] == 0){
                $a[$k] = 0;
            }else{
                $a[$k] = round($v['score']/$v['num'],2);
            }

        }

        asort($a);
        $temp = $a;
    }

    public function total_sort($total)
    {
        $a = $total;
        $name = $score = array();
        $tscore = $num = 0;
        foreach ($a as $key => $row)
        {
            $score[$key]  = $row['score'];
        }

        array_multisort($score, SORT_ASC,  $a);

        foreach($a as $k=>$v){
            $name[] = $v['name'];
            $score[] = $v['score'];
            if(isset($v['score']) && $v['score'] > 0){
                $tscore += $v['score'];
                $num ++;
            }
        }

        if($num == 0){
            $data = array('name'=>$name,'score'=>$score,'avg'=>0);
        }else{
            $data = array('name'=>$name,'score'=>$score,'avg'=>round($tscore/$num,2));
        }
        return $data;
    }
}
